import { MenuDataItem } from '@ant-design/pro-layout';
import { AuthButton, ButtonItem, RouteItem } from './Auth';
import { reloadAuthorized } from './Authorized';
import { IconMap } from './icons';
import { userStoarge } from './Storage';

// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str?: string): string | string[] {
  const authorityString =
    typeof str === 'undefined' && localStorage ? localStorage.getItem('antd-pro-authority') : str;
  // authorityString could be admin, "admin", ["admin"]
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }
  // preview.pro.ant.design only do not use in your production.
  // preview.pro.ant.design 专用环境变量，请不要在你的项目中使用它。
  if (!authority && ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return ['admin'];
  }
  return authority;
}

export function setAuthority(authority: string | string[]): void {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
  localStorage.setItem('antd-pro-authority', JSON.stringify(proAuthority));
  // auto reload
  reloadAuthorized();
}

/**
 * localStorage中获取路由信息
 */
export function getRoutes(): string[] {
  // let routesStr;
  let routes;
  try {
    routes = userStoarge.getItem('agree-routes');
    // if (routesStr) {
    //   routes = JSON.parse(routesStr);
    // }
  } catch (error) {
    console.error(error);
    routes = [];
  }
  return routes;
}

/**
 * 将路由信息数组转json字符串，并保存在localStorage中
 */
export function setRoutes(routes: string[]) {
  userStoarge.removeItem('agree-routes');
  userStoarge.setItem('agree-routes', routes);
}

export function deleteRoutes() {
  userStoarge.removeItem('agree-routes');
}

/**
 * 获取应用的全部按钮集合
 * @returns 按钮集合
 */
export function getButtons(): AuthButton[] {
  let buttons = [];
  try {
    buttons = userStoarge.getItem('agree-buttons');
    if (!buttons) {
      buttons = [];
    }
  } catch (error) {
    buttons = [];
  }
  return buttons;
}

/**
 * 获取指定页面的按钮集合
 * @param pageCode 页面权限编码，预先设置的
 * @returns 按钮集合
 */
export function getButton(pageCode: string): ButtonItem[] {
  const buttons: AuthButton[] = getButtons();
  if (!buttons) {
    new Array<ButtonItem>()
  }
  const data: AuthButton[] = buttons.filter(item => {
    const { code } = item;
    if (code === pageCode) {
      return true;
    }
    return false;
  });
  return data.length === 0 ? new Array<ButtonItem>() : data[0].buttons;
}

/**
 * 将按钮集合数组转json字符串，并保存在sessionStorage中
 */
export function setButtons(buttons: string | AuthButton[]) {
  userStoarge.removeItem('agree-buttons');
  userStoarge.setItem('agree-buttons', buttons);
}

export function deleteButtons() {
  userStoarge.removeItem('agree-buttons');
}

/**
 * 将token字符串保存在sessionStorage中
 * @param token token字符串
 */
export function saveToken(token: string) {
  // console.info(token);
  userStoarge.setItem('agree-token', token);
}

/**
 * 从sessionStorage中获取token字符串
 * @returns token字符串
 */
export function getToken(): string {
  let token = userStoarge.getItem('agree-token');
  // console.info(token);
  if (!token) {
    console.error('token不存在');
    token = "";
  }
  return token;
}

/**
 * 删除保存在sessionStorage中的token字符串
 */
export function deleteToken() {
  userStoarge.removeItem('agree-token');
}

/**
 * 将userId保存在sessionStorage中
 * @param userId 当前登录用户的id
 */
export function saveCurrentLoginUserId(userId: string) {
  // console.info(userId);
  userStoarge.setItem('agree-user-id', userId);
}

/**
 * 将userName保存在sessionStorage中
 * @param userName 当前登录用户名
 */
export function saveCurrentLoginUser(userName: string) {
  userStoarge.setItem('agree-user', userName);
}

/**
 * 从sessionStorage中获取当前登录用户的id
 * @returns 当前登录用户的id
 */
export function getCurrentLoginUserId(): string {
  let userId = userStoarge.getItem('agree-user-id');
  console.info('userId', userId);
  if (!userId) {
    console.error('userId不存在');
    userId = "";
  }
  return userId;
}

/**
 * 从sessionStorage中获取当前登录用户
 * @returns 当前登录用户名
 */
export function getCurrentLoginUser(): string {
  let userName = userStoarge.getItem('agree-user');
  console.info('userName', userName);
  if (!userName) {
    console.error('userId不存在');
    userName = "";
  }
  return userName;
}

/**
 * 删除保存在sessionStorage中的userId
 */
export function deleteCurrentLoginUserId() {
  return userStoarge.removeItem('agree-user-id');
}

/**
 * 这里做了个转换，可能服务端返回的接口格式和前端的路由格式并不一致，
 * 可以在这个方法里进行调整，这里的方法仅作参考，根据自己实际情况进行调整即可
 * @param routes 服务端返回的路由菜单数据
 * @returns 转换后的菜单结果
 */
export const menuFormatter = (routes: RouteItem[]) => {
  const menuData = routes.map((item: RouteItem) => {
    // console.info('hideMenu', item.hideMenu);
    // 菜单隐藏
    // if (item.hideMenu === true) {
    //   return;
    // }
    const result: MenuDataItem = {
      // children : menuFormatter(item.children),
      name: item.code,
      path: item.route === null ? '/' : item.route,
      icon: IconMap[item.icon] || IconMap[''.concat(item.icon, 'Outlined')],
      hideInMenu: item.hideInMenu,
    };
    if (item.children) {
      const children = menuFormatter(item.children);
      result.children = children;
    }
    return result;
  });
  const menuData2 = menuData.filter(item => item != undefined); // 将空值或undefined过滤掉
  // console.info('menuData', menuData);
  return menuData2;
}

/**
 * 按钮集合处理，将服务端的返回整理成浏览器本地所需的数据结构
 * @param {*} buttons json对象按钮集合
 * @returns 处理后的按钮集合，页面下所有的按钮
 */
export function formatButtons(buttons: ButtonItem[]): AuthButton[] {
  return buttons.map(item => {
    // 匹配按钮
    let buttons: ButtonItem[] = [];
    if (item.children) {
      buttons = item.children.map(item => {
        return {
          action: item.action,
          alias: item.alias,
          code: item.code,
          name: item.name,
          path: item.route
        }
      })
    }
    return {
      code: item.code,
      buttons
    };
  });
}

/**
 * 路由菜单国际化处理
 * @param routes 路由集合
 * @param parentName 父菜单名
 * @returns
 */
export const getFormatterMenuData = (routes: RouteItem[], parentName: string | undefined) => {
  // 先过滤非法值
  const newRoutes = routes.filter(item => item!.code || item!.route);
  // 菜单名国际化
  return newRoutes.map(item => {
    // console.info('item', item);
    let locale = 'menu';
    // 父节点name值
    if (parentName) {
      locale = `${parentName}.${item.code}`;
    } else {
      locale = `menu.${item.code}`;
    }
    // console.info(locale);
    const { route } = item;
    const result = {
      ...item,
      name: locale,
      path: route
    };
    if (item.children) {
      const children = getFormatterMenuData(item.children, locale);
      // Reduce memory usage
      result.children = children;
    }
    return result;
  });
}

/**
 * 获取面包屑映射
 * @param {Object} menuData 菜单配置
 */
export const getBreadcrumbNameMap = (menuData: RouteItem[]) => {
  const routerMap = {};
  const flattenMenuData = (data: RouteItem[]) => {
    data.forEach(menuItem => {
      if (menuItem.children) {
        flattenMenuData(menuItem.children);
      }
      // Reduce memory usage
      routerMap[menuItem.route] = menuItem;
    });
  };
  flattenMenuData(menuData);
  return routerMap;
};

/**
 * 根据页面代码和按钮代码，判断是否有权限
 * @param {string} pageCode 页面代码
 * @param {string} btnCode 按钮代码
 * @returns 是否有权限，true-有按钮权限
 */
export const hasButtonPermission = (pageCode: string, btnCode: string) => {
  // 获取页面代码的按钮列表
  const btns = getButton(pageCode) || [];
  if (!btns || btns.length === 0) {
    return false;
  }
  return btns.some(btn => {
    return btn.alias === btnCode
  });
}